<?php

namespace App\V3\V3_1\Controllers;

use App\V3\V3_1\Models\AdminAddendumModel;
use App\V3\V3_1\Models\ExpressModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class ExpressController extends BaseController
{
    public function discriminateExpressCode(Request $request)
    {
        if($this->expressCheckTimes() == 0) {
            return $this->fail('', '快递查询次数不足，无法使用');
        }

        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'code' =>'required',//当前页
        ],[
            'code.required' => '`快递单号`缺失',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        //type 快递类型
        $type = isset($data['type'])?(in_array($data['type'], [0,1])?$data['type']:0):0;


        //验证本地库
        $codeInfo = ExpressModel::where('num',$data['code'])->first();

        if(empty($codeInfo)) {
            $comCodeInfo= self::autoNumber($data['code']);

            if(empty($comCodeInfo)) {
                $result = '';
            }
            else {
                //每次查询扣除
                if($this->expressCheckTimes() != -1) {
                    AdminAddendumModel::where('main_id', $this->getMainUserId())->decrement('express_check_times');
                }

                $comCode = $comCodeInfo[0]['comCode'];

                $param = array (
                    'com' => $comCode,  //快递公司编码
                    'num' => $data['code'],           //快递单号
                );

                $result = self::expressData($param);
                $result['name'] = $comCodeInfo[0]['name'];

                if($result['message'] == 'ok') {
                    if($result['ischeck']) {
                        ExpressModel::insert([
                            'num' => $param['num'],
                            'info' => json_encode($result),
                            'created_at' => time()
                        ]);
                    }
                }
                else {
                    return $this->fail('', $result['message']);
                }
            }
        }
        else {
            $result = json_decode($codeInfo['info'],true);
        }

        return $this->success($result);
    }

    public function autoNumber($code)
    {

        //请求参数
        $post_data = array();
        $post_data["key"] = config('app.kuaidi100_key');
        $post_data["num"] = $code;
        $url = 'http://www.kuaidi100.com/autonumber/auto';    //智能判断请求地址

        $params = "";
        foreach ($post_data as $k=>$v) {
            $params .= "$k=".urlencode($v)."&";              //默认UTF-8编码格式
        }
        $post_data = substr($params, 0, -1);
        return $this->curl($url,$post_data);
//        return response()->json([
//            'code' => 0,
//            'msg' => '查询成功',
//            'data' => $result
//        ]);
    }

    public function expressData($param){
        //参数设置
//        $key = 'RqgkGBrs8425';                        //客户授权key
//        $customer = 'D4A42D6E31AFA321957DE31AE520A4B5';     //查询公司编号
        //请求参数
        $post_data = array();
        $post_data["customer"] = config('app.kuaidi100_customer');
        $post_data["param"] = json_encode($param);
        $sign = md5($post_data["param"].config('app.kuaidi100_key').$post_data["customer"]);
        $post_data["sign"] = strtoupper($sign);

        $url = 'http://poll.kuaidi100.com/poll/query.do';    //实时查询请求地址

        $params = "";
        foreach ($post_data as $k=>$v) {
            $params .= "$k=".urlencode($v)."&";              //默认UTF-8编码格式
        }
        $post_data = substr($params, 0, -1);
        $result = $this->curl($url,$post_data);
        if(!isset($result['status'])){
            return $result;
        }
//        //入库
//        if($result['state']==3){
//            $expressModel = new ExpressModel();
//            $expressModel->num = $param['num'];
//            $expressModel->info =json_encode($result);
//            $expressModel->save();
//        }
        return $result;
    }

    public function curl($url,$post_data){
        //发送post请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        return json_decode(curl_exec($ch),true);
    }
}
